package com.msb.user_provider;

import com.msb.user_api.IUserApi;
import com.msb.user_api.Person;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
public class UserController implements IUserApi {

    @Value("${server.port}")
    String port;

    private AtomicInteger count = new AtomicInteger();

    @GetMapping("/alive")
    public String alive(){
        try {
            System.out.println("开始睡眠 500");
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        int i = count.incrementAndGet();
        System.out.println(port + " ->调用，第："+i + "  调用");
        //System.out.println("proider user alive: " + port);
        return "alive: " + port;
    }



    /**
     * @RequestParam("id")注解是可以删除的
     * @param id
     * @return
     */
    @GetMapping("/getMap")
    public Map<Integer, String> getMap(@RequestParam("id") Integer id) {
        System.out.println(id);
        return Collections.singletonMap(id, String.valueOf(new Random().nextInt(100)));
    }

    /**
     * @RequestParam("id") @RequestParam("name") 两个都可以删除
     * @param id
     * @param name
     * @return
     */
    @GetMapping("/getMap2")
    public Map<Integer, String> getMap2(@RequestParam("id") Integer id,@RequestParam("name") String name) {
        // TODO Auto-generated method stub
        System.out.println(id);
        return Collections.singletonMap(id, name);
    }

    /**
     * @RequestParam 不可以删除
     * @param map
     * @return
     */
    @GetMapping("/getMap3")
    public Map<Integer, String> getMap3(@RequestParam Map<String, Object> map) {
        // TODO Auto-generated method stub
        System.out.println(map);
        return Collections.singletonMap(Integer.parseInt(map.get("id").toString()), map.get("name").toString());
    }


    @PostMapping("/postMap")
    public Map<Integer, String> postMap(@RequestBody Map<String, Object> map) {
        // TODO Auto-generated method stub
        System.out.println(map);
        return Collections.singletonMap(Integer.parseInt(map.get("id").toString()), map.get("name").toString());
    }

    /**
     * PostMapping 注解会从接口中继承过来，所以不用再写
     * @param person
     * @return
     */
    @Override
    public Person postPerson(Person person) {
        System.out.println(ToStringBuilder.reflectionToString(person));
        return person;
    }

  /*  @Override
    public Person postPserson(Person person) {
        System.out.println(ToStringBuilder.reflectionToString(person));
        return person;
    }*/

}
